package com.jay.net.clazz;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Inet46AddressCls {
	public static void main(String[] args) throws Exception {
		getLocalIP();
	}

	static void determineIP(String name) throws UnknownHostException {
		InetAddress address = InetAddress.getByName(name);
		System.out.println("IP:　" + address.getHostAddress());
		switch (address.getAddress().length) {
		case 4:
			System.out.println("根据byte数组长度判断这个IP地址是IPv4地址!");
			break;
		case 16:
			System.out.println("根据byte数组长度判断这个IP地址是IPv6地址!");
			break;
		}
		if (address instanceof Inet4Address)
			System.out.println("使用instanceof判断这个IP地址是IPv4地址!");
		else if (address instanceof Inet6Address)
			System.out.println("使用instanceof判断这个IP地址是IPv6地址!");
	}

	public static void getLocalIP() throws Exception {
		Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
				.getNetworkInterfaces();
		while (e1.hasMoreElements()) {
			NetworkInterface ni = (NetworkInterface) e1.nextElement();
			System.out.println(ni.getName() + ":");
			Enumeration<?> e2 = ni.getInetAddresses();
			while (e2.hasMoreElements()) {
				InetAddress ia = (InetAddress) e2.nextElement();
				if (ia instanceof Inet6Address) {
					System.out.println("IPv6 is " + ia.getHostAddress());
					System.out.println("IPv4 compatible? "
							+ ((Inet6Address) ia).isIPv4CompatibleAddress());
				} else {
					System.out.println("IPv4 is " + ia.getHostAddress());
				}
			}
			System.out.print("\n");
		}
	}

}
